<template>
  <div class="config-model">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="0">
            <a-col :md="6" :sm="24">
              <a-form-item label="网关名称">
                <a-select
                  :showSearch="true"
                  optionFilterProp="children"
                  style="width: 100%"
                  v-model="queryParam.gatewayId"
                  allow-clear
                  placeholder="请选择网关名称"
                >
                  <a-select-option v-for="(item, ind) in gatewayList" :key="ind" :value="item.id">{{ item.gatewayName
                  }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span
                class="table-page-search-submitButtons"
                style="padding-left: 16px;"
              >
                <a-form-item label="故障等级">
                  <a-select
                    :showSearch="true"
                    optionFilterProp="children"
                    style="width: 100%"
                    v-model="queryParam.failureLevelId"
                    allow-clear
                    placeholder="请选择故障等级"
                  >
                    <a-select-option v-for="(item, ind) in failureLevelList" :key="ind" :value="item.code">{{ item.value }}</a-select-option>
                  </a-select>
                </a-form-item>
              </span>
            </a-col>
            <a-col :md="6" :sm="24">
              <span
                class="table-page-search-submitButtons"
                style="float: left;padding-left: 16px;"
              >
                <a-button
                  type="primary"
                  class="btn_search_reset"
                  @click="$refs.table.refresh()"><a-icon type="search"/>查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  class="btn_search_reset"
                  @click="
                    () => {
                      queryParam = { deviceIds: deviceIds.toString() }
                      $refs.table.refresh()
                    }
                  "><a-icon type="reload"/>重置</a-button>
              </span>
            </a-col>
            <a-col :md="6" :sm="24">
              <span
                class="table-page-search-submitButtons"
                style="float: right;"
              >
                <a-button type="primary" class="btn_add" @click="syncModel">同步模型</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        id="table-wrapper"
        ref="table"
        size="middle"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.id"
      >
        <span slot="channel" slot-scope="text, record">{{ getChannelNo(record.expectGroupId) }}</span>
        <span slot="fileId" slot-scope="text, record">
          <a @click="$refs.playForm.play(record)">{{ text === null || text === '' ? '无' : '播放' }}</a>
        </span>
        <span slot="failureLevel" slot-scope="text">
          {{ failureLevelFilter(text) }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
            <a class="btn_del">删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <play-form ref="playForm" @ok="handleOk"/>
      <task-progress-dlg ref="taskProgressDlg" @ok="handleOk"/>

    </a-card>
  </div>
</template>

<script>

  import { STable } from '@/components'
  import { page, del, sync } from '@/api/modular/main/bizcollectionmodelmanage/collectionModelManage'
  import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'
  import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
  import playForm from '../bizcollectionsmodelmanage/playForm'
  import taskProgressDlg from '../bizcollectionsamplemanage/taskProgressDlg'

  export default {
    components: {
      STable,
      playForm,
      taskProgressDlg
    },
    props: {
      stationId: {
        type: Number,
        require: false
      }
    },
    created () {
      this.queryParam.deviceIds = this.deviceIds.toString()
      try {
        this.$refs.table.refresh()
      } catch (e) {
        // 首次进入界面，因表格加载顺序，会抛异常，我们不予理会
      }
      this.getFailureLevelList()
      const param = {
        stationId: this.stationId
      }
      this.queryParam.stationId = this.stationId
      gatewayList(param).then(res => {
        this.gatewayList = res.data
      })
    },
    data () {
      return {
        data: [],
        page: {},
        loading: false,
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [
          // 表头
          {
            title: '网关名称',
            dataIndex: 'gatewayName'
          },
          {
            title: '模型名称',
            dataIndex: 'faultName'
          },
          {
            title: '故障等级',
            dataIndex: 'failureLevel',
            scopedSlots: { customRender: 'failureLevel' },
            align: 'center'
          },
          {
            title: '通道',
            dataIndex: 'channel',
            scopedSlots: { customRender: 'channel' },
            align: 'center'
          },
          {
            title: '期望ID编号',
            dataIndex: 'expectAccessToken'
          },
          {
            title: '期望分组',
            dataIndex: 'expectGroupId'
          },
          {
            title: '上报时间',
            dataIndex: 'createTime',
            align: 'center',
            width: 150
          },
          {
            title: '模型文件库',
            dataIndex: 'fileId',
            scopedSlots: { customRender: 'fileId' },
            align: 'center'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: 'center'
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then(res => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        treeList: [],
        treeLoading: true,
        gatewayList: [],
        deviceIds: [],
        stationTreeIndex: -1,
        failureLevelList: []
      }
    },
    methods: {
      getChannelNo (text) {
        return text.charAt(text.length - 1)
      },
      failureLevelFilter (record) {
        let str = ''
        this.failureLevelList.forEach(item => {
          if (record === item.code) {
            str = item.value
          }
        })
        return str
      },
      getFailureLevelList () {
        sysDictTypeDropDown({ code: 'fault_level' }).then((res) => {
          if (res.success) {
            this.failureLevelList = res.data
          }
        })
      },
      del (record) {
        del(record)
          .then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('删除失败：' + res.message)
            }
          })
          .catch(err => {
            this.$message.error('删除错误：' + err.message)
          })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getGatewayList (stationId) {
        gatewayList({ stationId: stationId }).then(res => {
          if (res.success) {
            this.gatewayList = res.data
            this.gatewayIds = []
            this.gatewayList.filter(value => {
              this.gatewayIds.push(value.id)
            })
            this.queryParam.gatewayIds = this.gatewayIds.toString()
            this.handleOk()
          }
        })
      },
      syncModel () {
        if (typeof (this.queryParam.gatewayId) === 'undefined') {
          this.$message.error('请选择需要同步模型的网关')
          return
        }
        sync({ gatewayId: this.queryParam.gatewayId })
          .then(res => {
            if (res.success) {
              const param = {
                type: 3,
                taskId: res.data,
                gatewayId: this.queryParam.gatewayId
              }
              this.$refs.taskProgressDlg.init(param)
              this.$refs.table.refresh()
            } else {
              this.$message.error('同步失败' + res.message)
            }
          })
          .catch(err => {
            this.$message.error('同步错误：' + err.message)
          })
      }
    }
  }
</script>

<style lang="less">
  @import '../../../assets/css/list.less';

  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>
>
